const UserModel = require('../models/User.js');
var { createToken, verifyToken } = require('../utils/jsonwebtoken');
const bcrypt = require('bcryptjs')
const salt = bcrypt.genSaltSync(10); //加密十次

module.exports = {
    async signup(ctx) {
        let saltPassword = ''
        const { phone, password } = ctx.request.body
        // 如果数据库里已经有这个手机号，说明被注册过了，报错！
        const one = await UserModel.findOne({ phone: phone })
        if (one) {
            ctx.body = {
                success: true,
                msg: '手机号已经注册过了喔！'
            }
            return;
        }
        await bcrypt.hash(password, salt).then(res => {
            saltPassword = res
        })
        // 注册一个新用户
        const result = await UserModel.create({
            phone: phone,
            password: saltPassword
        })  //将数据填充到 model/user.js里面
        if (result) {
            ctx.body = {
                success: true,
                data: result
            }
        } else {
            ctx.body = {
                success: true,
                msg: '注册失败,请重试!'
            }
        }


    },
    async login(ctx) {
        let flag = false;
        const user_data = ctx.request.body
        const one = await UserModel.findOne({
            phone: user_data.phone,
        })
        await bcrypt.compare(user_data.password, one.password).then(res => {
            flag = res
        })
        //将数据填充到 model/user.js里面
        if (flag) {
            var tokenor = { _id: one._id, username: one.phone, password: one.password };
            var token = createToken(tokenor);
            ctx.body = {
                success: true,
                data: one,
                token
            }
        } else {
            ctx.body = {
                success: false,
                msg: '用户名或者密码错误'
            }
        }
    },

    async verifyToken(ctx) {
        var token = ctx.request.headers.token
        let token_data = verifyToken(token)
        if (token_data) {
            let username = token_data.username
            let password = token_data.password
            const one = await UserModel.findOne({ phone: username })
            if (password == one.password) {
                ctx.body = {
                    success: true,
                    msg: 'token验证成功',
                }
            }
        } else {
            ctx.body = {
                success: false,
                msg: '请登录',
            }
        }
    },

    async getUserInfo(ctx) {
        var token = ctx.request.headers.token
        let token_data = verifyToken(token);
        const one = await UserModel.findById(token_data._id, { password: 0 }).populate('likeNotes');
        ctx.body = {
            success: true,
            data: one
        }
    },

    async updateUserInfo(ctx) {
        var token = ctx.request.headers.token
        let token_data = verifyToken(token);
        const data = ctx.request.body
        let updateData = data.data;
        let flag = false;

        if (data.changesItemName == 'password') {
            let me = await UserModel.findOne({
                phone: token_data.username,
            })

            await bcrypt.compare(data.oldPassword, me.password).then(res => {
                flag = res
            })
            if (!flag) {
                ctx.body = {
                    sucstcess: false,
                    msg: "原密码错误，修改失败！"
                }
                return
            }
            await bcrypt.hash(updateData, salt).then(res => {
                updateData = res
            })
        }
        const one = await UserModel.findOneAndUpdate({ _id: token_data._id }, { [data.changesItemName]: updateData });
        if (one) {
            ctx.body = {
                success: true,
                msg: "修改成功！",
                data: one
            }
        }
    },
    async updateUserName(ctx) {

    },
    async getUserInfoById(ctx) {
        const { id } = ctx.request.body
        let one = await UserModel.findById(id).populate('likeNotes')
        if (one) {
            ctx.body = {
                success: true,
                data: one
            }
        } else {
            ctx.body = {
                success: true,
                msg: "未找到该用户信息"
            }
        }
    },
    async addFollower(ctx) {
        let { followerId } = ctx.request.body
        var token = ctx.request.headers.token
        let token_data = verifyToken(token);
        let res1 = await UserModel.findByIdAndUpdate(token_data._id, {
            $push:
            {
                "followers": followerId
            }
        })
        // 点赞的别人的粉丝数也要变
        let res2 = await UserModel.findByIdAndUpdate(followerId, {
            $push:
            {
                "fans": token_data._id
            }
        })
        ctx.body = {
            success: true,
            msg: '关注成功'
        }

    },
    async cancelFollower(ctx) {
        let { followerId } = ctx.request.body
        var token = ctx.request.headers.token
        let token_data = verifyToken(token);
        let res1 = await UserModel.findByIdAndUpdate(token_data._id, {
            $pull:
            {
                "followers": followerId
            }
        })
        // 点赞的别人的粉丝数也要变
        let res2 = await UserModel.findByIdAndUpdate(followerId, {
            $pull:
            {
                "fans": token_data._id
            }
        })
        ctx.body = {
            success: true,

            msg: '取消关注'
        }
    },
    // async getFollower(ctx) {
    //     var token = ctx.request.headers.token
    //     let token_data = verifyToken(token)
    //     if (token_data) {
    //         let username = token_data.username
    //         let password = token_data.password
    //         const one = await UserModel.findOne({ phone: username })
    //         if (password == one.password) {
    //             ctx.body = { success:true,
    //                 msg: 'token验证成功',
    //             }
    //         }
    //     } else {
    //         ctx.body = { success:true,
    //             msg: '身份认证过期，请重新登陆',
    //         }
    //     }
    // },
    // async getFans(ctx) {

    // }

}




